//
//  Player.m
//  喜马拉雅FM
//
//  Created by dllo on 16/3/4.
//  Copyright © 2016年 lanou.com. All rights reserved.
//

#define WIDTH [UIScreen mainScreen].bounds.size.width
#define HEIGHT [UIScreen mainScreen].bounds.size.height

#import "Player.h"
#import <AVFoundation/AVFoundation.h>
#import <UIKit/UIKit.h>
#import "ModelForSecendVC.h"
#import "UIImageView+WebCache.h"

@interface Player ()

// 播放器对象.
@property (nonatomic, retain) AVPlayer *player;

// 播放器容器.
@property (nonatomic, retain) UIView *container;

// 播放/暂停.
@property (nonatomic, retain) UIButton *playOrPause;
// 下一曲.
@property (nonatomic, retain) UIButton *buttonRight;
// 上一曲.
@property (nonatomic, retain) UIButton *buttonLeft;

// 播放进度.
@property (nonatomic, retain) UIProgressView *progress;
// 毛玻璃视图.
@property (nonatomic, retain) UIVisualEffectView *visualView;

@property (nonatomic, retain) UILabel *labelForTitle;
@property (nonatomic, retain) UIImageView *pictureForAlbumImage;


@property (nonatomic, retain) AVPlayerItem *playerItem;
@property (nonatomic, assign) CGFloat totalMusicDuration;
@property (nonatomic, retain) UISlider *progressSlider;

@end

@implementation Player

+ (instancetype)sharePlayer {
    
    // 在静态区,只初始化一次 创建ItemVC3对象.
    static Player *player = nil;
    static dispatch_once_t predicate;
    
    dispatch_once(&predicate, ^{
        player = [[Player alloc]init];
    });
    
    return player;
}


- (instancetype)init {
    self = [super init];
    if (self) {
        
    }
    return self;
}

- (void)dealloc {
    
    [self removeObserverFromPlayerItem:self.player.currentItem];
    [self removeNotification];
    [super dealloc];
    
}

- (void)playWithUrl:(NSURL *)url showView:(UIView *)showView DataForModel:(ModelForSecendVC *)model {

    // 毛玻璃视图层.
    UIImageView *imageView = [[UIImageView alloc]init];
    [imageView sd_setImageWithURL:[NSURL URLWithString:model.coverLarge]];
    imageView.frame = showView.bounds;
    [showView addSubview:imageView];
    imageView.userInteractionEnabled = YES;
    [imageView release];
    
    UIBlurEffect *blur = [UIBlurEffect effectWithStyle:2];
    self.visualView = [[UIVisualEffectView alloc]initWithEffect:blur];
    self.visualView.frame = showView.bounds;
    [imageView addSubview:self.visualView];
    [self.visualView release];
    
    
    
    self.progress = [[UIProgressView alloc]initWithProgressViewStyle:UIProgressViewStyleDefault];
    self.progress.frame = CGRectMake(50, HEIGHT - 200, [UIScreen mainScreen].bounds.size.width - 100, 30);
    self.progress.backgroundColor = [UIColor greenColor];
    [self.visualView.contentView addSubview:self.progress];
    [self.progress release];
    
    //    self.progressSlider = [[UISlider alloc]initWithFrame:CGRectMake(50, HEIGHT - 220, WIDTH - 100, 30)];
    //    [self.visualView.contentView addSubview:self.progressSlider];
    //    [self.progressSlider addTarget:self action:@selector(progressAction:) forControlEvents:UIControlEventValueChanged];
    //    [self.progressSlider release];
    //
    //    self.progressSlider.minimumValue = 0;
    //    self.progressSlider.maximumValue = self.totalMusicDuration;
    
    self.playOrPause = [UIButton buttonWithType:UIButtonTypeCustom];
    self.playOrPause.frame = CGRectMake((WIDTH - 50) / 2, HEIGHT - 150, 50, 50);
    [self.visualView.contentView addSubview:self.playOrPause];
    [self.playOrPause setBackgroundImage:[UIImage imageNamed:@"zanting2"] forState:UIControlStateNormal];
    [self.playOrPause addTarget:self action:@selector(handleAction:) forControlEvents:UIControlEventTouchUpInside];
    
    
    self.buttonRight = [UIButton buttonWithType:UIButtonTypeCustom];
    self.buttonRight.frame = CGRectMake((WIDTH - 50) / 2 + 70, HEIGHT - 150, 50, 50);
    [self.visualView.contentView addSubview:self.buttonRight];
    [self.buttonRight setBackgroundImage:[UIImage imageNamed:@"xiayiqu"] forState:UIControlStateNormal];
    [self.buttonRight addTarget:self action:@selector(handleButtonRight:) forControlEvents:UIControlEventTouchUpInside];
    
    self.buttonLeft = [UIButton buttonWithType:UIButtonTypeCustom];
    self.buttonLeft.frame = CGRectMake((WIDTH - 50) / 2 - 70, HEIGHT - 150, 50, 50);
    [self.visualView.contentView addSubview:self.buttonLeft];
    [self.buttonLeft setBackgroundImage:[UIImage imageNamed:@"shangyiqu"] forState:UIControlStateNormal];
    [self.buttonLeft addTarget:self action:@selector(handleButtonLeft:) forControlEvents:UIControlEventTouchUpInside];
    
    
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(10, 24, 32, 32);
    [backButton setBackgroundImage:[UIImage imageNamed:@"fanhui"] forState:UIControlStateNormal];
    [self.visualView.contentView addSubview:backButton];
    [backButton addTarget:self action:@selector(backButton:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *naozhongButton = [UIButton buttonWithType:UIButtonTypeCustom];
    naozhongButton.frame = CGRectMake(WIDTH - 40, 24, 32, 32);
    [naozhongButton setBackgroundImage:[UIImage imageNamed:@"naozhong"] forState:UIControlStateNormal];
    [self.visualView.contentView addSubview:naozhongButton];
    
    self.labelForTitle = [[UILabel alloc]initWithFrame:CGRectMake(50, 20, WIDTH - 100, 60)];
    [self.visualView.contentView addSubview:self.labelForTitle];
    self.labelForTitle.text = model.title;
    self.labelForTitle.font = [UIFont systemFontOfSize:20];
    self.labelForTitle.textColor = [UIColor grayColor];
    self.labelForTitle.numberOfLines = 0;
    self.labelForTitle.textAlignment = NSTextAlignmentCenter;
    [self.labelForTitle release];
    
    
    self.pictureForAlbumImage = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"2.jpg"]];
    self.pictureForAlbumImage.frame = CGRectMake((WIDTH - (HEIGHT - 60 - 300)) / 2, 110, HEIGHT - 60 - 300, HEIGHT - 60 - 300);
    [self.visualView.contentView addSubview:self.pictureForAlbumImage];
    [self.pictureForAlbumImage sd_setImageWithURL:[NSURL URLWithString:model.coverLarge] placeholderImage:[UIImage imageNamed:@"2.jpg"]];
    
    // playerItem初始化.
      AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:url];
    
    // player初始化
    self.player = [AVPlayer playerWithPlayerItem:playerItem];
    [self addProgressObserver];
    [self addObserverToPlayerItem:playerItem];
    [self.player play];
}

// 返回按钮方法实现.
- (void)backButton:(UIButton *)button {
    
    NSNotification *notice = [NSNotification notificationWithName:@"返回" object:nil];
    [[NSNotificationCenter defaultCenter]postNotification:notice];
}

#pragma mark UIButton的点击方法.
// 播放按钮的点击事件
- (void)handleAction:(UIButton *)button {
    
    if (button.selected) {
        [self.playOrPause setBackgroundImage:[UIImage imageNamed:@"zanting2"] forState:UIControlStateNormal];
        [self.player play];
    }else {
        [self.playOrPause setBackgroundImage:[UIImage imageNamed:@"bofang2"] forState:UIControlStateNormal];
        [self.player pause];
    }
     button.selected = !button.selected;
}

- (void)handleButtonRight:(UIButton *)button {

    NSNotification *notice = [NSNotification notificationWithName:@"下一曲" object:nil];
    [[NSNotificationCenter defaultCenter]postNotification:notice];
}

- (void)handleButtonLeft:(UIButton *)button {

    NSNotification *notice = [NSNotification notificationWithName:@"上一曲" object:nil];
    [[NSNotificationCenter defaultCenter]postNotification:notice];
    
}


#if 0
{
    //========================================================
#pragma mark 播放器
    - (void)addAVPlayer {
        
        NSURL *url = [NSURL URLWithString:self.musicUrlString];
        self.playerItem = [AVPlayerItem playerItemWithURL:url];
        self.player = [AVPlayer playerWithPlayerItem:self.playerItem];
        [_playerItem release];
        
    }
    
    - (void)addNotificationCenters {
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(musicPlayDidEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
        
    }
    
    - (void)musicPlayDidEnd:(NSNotification *)notify {
        
        NSLog(@"播放结束");
    }
    
    - (void)addProgressObserverAAA {
        
        [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
            
            // 总时长
            CGFloat duration = CMTimeGetSeconds(self.playerItem.duration);
            // 当前时间
            CGFloat current = CMTimeGetSeconds(self.player.currentTime);
            // 倒计时.
            //        CGFloat rem = duration - current;
            //        NSString *totalTime = [NSString stringWithFormat:@"%02d:%02d",(int)rem/60,(int)rem%60];
            //        NSString *currenTime = [NSString stringWithFormat:@"%02d:%02d",(int)current/60 ,(int)current%60];
            
            // 保存总时长用于手动快进快退.
            self.totalMusicDuration = duration;
            
            // 设置进度值 当前时间/总时长.
            self.progressSlider.value = current/duration;
        }];
        
    }
    
    // 拖动进度条所触发的方法.
    - (void)progressAction:(UISlider *)slider {
        
        // 获取当前的时间.
        double currentTime = self.totalMusicDuration *slider.value;
        CMTime dragedCMTime = CMTimeMake(currentTime, 1);
        [self.player seekToTime:dragedCMTime completionHandler:^(BOOL finished) {
            [self.player play];
        }];
    }
    
    
    
    //========================================================
    
}
#endif

#pragma mark  私有方法.
- (void)createAVPlayerLayer {
    
    // 创建播放器层.
    //    AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    //    [self.visualView.layer addSublayer:playerLayer];
    //    playerLayer.frame = self.visualView.frame;
    //    playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
}



#pragma mark 监控

// 给播放器添加进度更新.
- (void)addProgressObserver {
   
    AVPlayerItem *playerItem = self.player.currentItem;
    UIProgressView *progress = self.progress;
    
    // 设置每秒执行一次.
    [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1.0, 1.0) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        float current = CMTimeGetSeconds(time);
        float total = CMTimeGetSeconds([playerItem duration]);
        //        NSLog(@"当前已经播放了%.2fs",current);
        if (current) {
            [progress setProgress:(current/total) animated:YES];
        }
    }];
}

// 给AVPlayerItem添加监控.
- (void)addObserverToPlayerItem:(AVPlayerItem *)playerItem {
 
    // 监控状态属性,注意AVPlayer也有一个status属性,通过监控它的status也可以获得播放的状态.
    [playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    
    // 监控网络加载情况的属性.
    [playerItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
}

// 移除AVPlayerItem上的监控.
- (void)removeObserverFromPlayerItem:(AVPlayerItem *)playerItem {
    NSLog(@"%s",__FUNCTION__);
    [playerItem removeObserver:self forKeyPath:@"status"];
    [playerItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
}

// 通过KVO监控播放器的状态. keyPath:监控属性, object:监视器, change:状态改变, context:上下文.
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    
    AVPlayerItem *playerItem = object;
    if ([keyPath isEqualToString:@"status"]) {
        AVPlayerStatus status = [[change objectForKey:@"new"] intValue];
        if (status == AVPlayerStatusReadyToPlay) {
            NSLog(@"正在播放.....,视频总长度为:%.2f",CMTimeGetSeconds(playerItem.duration));
        }
    }else if([keyPath isEqualToString:@"loadedTimeRanges"]) {
        NSArray *array = playerItem.loadedTimeRanges;
        // 本次缓冲范围.
        CMTimeRange timeRange = [array.firstObject CMTimeRangeValue];
        
        float startSecends = CMTimeGetSeconds(timeRange.start);
        float durationSecends = CMTimeGetSeconds(timeRange.duration);
        // 缓冲总长度.
        NSTimeInterval totalBuffer = startSecends + durationSecends;
        NSLog(@"共缓冲:%.2f",totalBuffer);
    }
}

#pragma mark 通知
// 添加播放器通知.
- (void)addNotification {
    NSLog(@"%s",__FUNCTION__);
    // 给AVPlayerItem添加播放完成通知.
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playBackFinished:) name:AVPlayerItemDidPlayToEndTimeNotification object:self.player.currentItem];
}

- (void)playBackFinished:(NSNotification *)notification {
    NSLog(@"%s",__FUNCTION__);
    NSLog(@"视频播放完成");
}

- (void)removeNotification {
    NSLog(@"%s",__FUNCTION__);
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
